package com.imooc.mall.exception;

import com.imooc.mall.common.ApiRestResponse;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * @author yijiu
 * @version 1.0
 * @description: 处理统一异常的handler
 * @date 2022/2/20 17:59
 */
//该注解用于拦截异常
//@ControllerAdvice    发现在使用过程中，无法捕获系统异常

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    //使用log工厂类生成一个log对象用于打印异常信息
    private final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    //注解规定处理的异常类型
    @ExceptionHandler(Exception.class)
    @ResponseBody    //之前忘记添加这个注解，导致无法返回信息
    public Object handleException(Exception e){
        //抛出系统异常
        logger.error("Default Exception:", e);
        return ApiRestResponse.error(ImoocMallExceptionEnum.SYSTEM_ERROR);
    }

    @ExceptionHandler(ImoocMallException.class)
    @ResponseBody
    public Object handleImoocMallException(ImoocMallException e) {
        logger.error("ImoocMallException:", e);
//        return ApiRestResponse.error(e.getCode(), e.getMessage());
        return ApiRestResponse.error(e.getCode(),e.getMessage());
    }


    //对参数校验的异常进行处理
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public ApiRestResponse handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        logger.error("MethodArgumentNotValidException: ",e);
        return handleBindingResult(e.getBindingResult());
    }

    @ExceptionHandler(BindException.class)
    private ApiRestResponse handleBindingResult(BindingResult result){
        //把异常处理为对外暴露的提示
        List<String> list = null;
        if (result.hasErrors()) {
            List<ObjectError> allErrors = result.getAllErrors();
            for (int i = 0; i < allErrors.size(); i++) {
                ObjectError objectError = allErrors.get(i);
                String message = objectError.getDefaultMessage();
                list.add(message);
            }
        }
        if (list.size() == 0) {
            return ApiRestResponse.error(ImoocMallExceptionEnum.REQUEST_PARAM_ERROR);
        }
        return ApiRestResponse.error(ImoocMallExceptionEnum.REQUEST_PARAM_ERROR.getCode(),list.toString());
    }
}
